<template>
    <el-dialog v-model="dialogFormShow" :title="state.dialog.title" width="60%" :before-close="onClose">
        <el-form ref="ruleFormRef" :model="state.form">

            <el-form-item label="问题内容" prop="content"
                :rules="[{ required: true, message: '请输入问题内容', trigger: 'blur' }]">
                <el-input v-model="state.form.content" autocomplete="off" clearable />
            </el-form-item>

            <el-form-item label="题目类型" prop="type">
                <el-radio-group v-model="state.form.type">
                    <el-radio :value="1">单选</el-radio>
                    <el-radio :value="2">多选</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="选择题组" prop="teamId"
                :rules="[{ required: true, message: '请选择题组', trigger: ['blur', 'change'] }]">
                <el-select v-model="state.form.teamId" placeholder="请选择题组" clearable>
                    <el-option v-for="(item, index) in state.teamList" :key="index" :label="item.teamName"
                        :value="item.id" />
                </el-select>
            </el-form-item>

            <el-row :gutter="35" v-for="(item, index) in state.form.answerList" :key="index">
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="12" class="mb20">
                    <el-form-item label="答案描述" :prop="`answerList[${index}].content`"
                        :rules="[{ required: true, message: `答案描述不能为空`, trigger: 'blur' }]">
                        <template #label>
                            <el-button type="primary" circle size="small" @click="onAddRowAnswer(index)"
                                v-if="index === 0">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-button>
                            <el-button type="danger" circle size="small" @click="onDelRow(index)" v-else>
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                            <span class="ml10">答案描述</span>
                        </template>
                        <el-input v-model="state.form.answerList[index].content" style="width: 100%"
                            placeholder="请输入" />

                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                    <el-form-item label="排序" :prop="`answerList[${index}].orderNum`"
                        :rules="[{ required: true, message: `排序不能为空`, trigger: 'blur' }]">
                        <el-input-number v-model="state.form.answerList[index].orderNum" :min="1"
                            controls-position="right" style="width: 100%" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                    <el-form-item label="是否为正确答案" :prop="`answerList[${index}].rightAnswerType`"
                        :rules="[{ required: true, message: `是否为正确答案`, trigger: 'change' }]">

                        <el-switch v-model="state.form.answerList[index].rightAnswerType"
                            @change="switchRightAnswer(item, index)" />

                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="排序" prop="orderNum">
                <el-input-number v-model="state.form.orderNum" controls-position="right" clearable autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button type="primary" @click="onSubmit">
                    {{ state.dialog.submitText }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Question, QuestionTeam } from '/@/api';
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
const dialogFormShow = ref(false)

const onOpen = (type, row) => {

    if (type == 'add') {
        state.dialog.title = "新增问题"
        state.dialog.submitText = '新 增'
        state.dialog.type = type
    } else if (type == 'edit') {
        state.dialog.title = "修改问题"
        state.dialog.type = type
        state.dialog.submitText = '修 改'
        state.form = JSON.parse(JSON.stringify(row))

    } else {
        console.log("选择弹出框的类型错误");
        return
    }
    dialogFormShow.value = true

}

const emits = defineEmits(['refresh'])

const onClose = () => {

    //此情况下不会生效，直接点修改的时候，所以表单初始化的信息就是row，这时候再重置也不会管用
    // ruleFormRef.value.resetFields()
    //直接赋值初始化操作
    state.form = {
        content: '',
        orderNum: '',
        teamId: '',
        type: 1, //题目类型:1-单选，2-多选
        answerList: [{
            content: '',
            orderNum: 1,
            //是否是正确答案
            rightAnswerType: false
        }]
    }
    ruleFormRef.value.resetFields()
    dialogFormShow.value = false;
}
const ruleFormRef = ref()

// 提交
const onSubmit = () => {

    if (!ruleFormRef.value) return
    ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            if (state.dialog.type === 'add') {
                await Question.addQuestion(state.form)
            } else if (state.dialog.type === 'edit') {
                await Question.editQuestion(state.form)
            }
            onClose(); // 关闭弹窗
            emits('refresh');
        } else {
            console.log('校验不通过', fields)
            return false;
        }
    })
    // setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};

const state = reactive({
    form: {
        content: '',
        orderNum: '',
        teamId: '',
        type: 1, //题目类型:1-单选，2-多选
        answerList: [{
            content: '',
            orderNum: 1,
            //是否是正确答案
            rightAnswerType: false
        }],
    },
    teamList: [],
    dialog: {
        title: '',
        submitText: '',
        type: ''
    }
})

const switchRightAnswer = (item, index) => {
    //判断改变的switch当前的状态，为true修改为false不做任何操作，改为true时判断此组switch是否已经有为true的按钮，有给出提示
    if (item.rightAnswerType == true && state.form.type == '1' && state.form.answerList.length > 0 ) {
        for (let i = 0; i < state.form.answerList.length; i++) {
            if (i !== index && state.form.answerList[i].rightAnswerType == true) {
                ElMessage.error("选择的问题类型为单选，正确答案只能为一个")
                item.rightAnswerType = false;
                break;
            }
        }
    }
}

//TODO 来回切换题目类型时，重置rightAnswerType为fasle

//新增一行答案信息
const onAddRowAnswer = (index) => {
    state.form.answerList.push({
        content: '',
        orderNum: 1,
        //是否是正确答案
        rightAnswerType: false
    })
}

// 删除行
const onDelRow = (index) => {
    state.form.answerList.splice(index, 1);
};

const initQuestionTeamList = async () => {
    await QuestionTeam.getTeamIdAndNameList().then((res) => state.teamList = res.data)
}

onMounted(() => {
    initQuestionTeamList()
})

defineExpose({
    onOpen
})
</script>

<style lang="scss" scoped></style>